<template>
    <div>
        <!-- 左箭头按钮，当 current <=1 时禁用 -->
        <button @click="emits('change', current - 1)" :disabled="current <= 1">&lt;</button>
        <!-- 显示当前页码 -->
        <!-- <span style="padding: 10px">{{ current }}</span> -->
        <button
            v-for="item in pager"
            :key="item"
            :class="{ active: item == current }"
            @click="emits('change', item)"
        >
            {{ item }}
        </button>
        <!-- 右箭头按钮，当 current >= total/pageSize 时禁用 -->
        <button
            @click="emits('change', current + 1)"
            :disabled="current >= Math.ceil(total / pageSize)"
        >
            &gt;
        </button>
    </div>
</template>
<style scoped>
.active {
    color: #f70;
}
</style>
<script setup>
import { ref, watch } from 'vue';

// 定义组件的 props 对象，其中每一项都是一个属性，它们都有不同的验证
var props = defineProps({
    // 总页数，必传，Number 类型，默认为 0
    total: {
        type: Number,
        required: true,
        default: 0,
    },
    // 当前页码，必传，Number 类型，默认为 1
    current: {
        type: Number,
        required: true,
        default: 1,
    },
    // 页面尺寸，必传，Number 类型，默认为 10
    pageSize: {
        type: Number,
        required: true,
        default: 10,
    },
});

// 定义组件的事件对象
const emits = defineEmits(['change']);
const pager = ref([]);

function makePager() {
    pager.value = [];
    var start = Math.max(props.current - 3, 1);
    var end = Math.min(Math.ceil(props.total / props.size), props.current + 3);

    if (end - start < 6) {
        start = Math.max(end - 6, 1);
        end = Math.min(Math.ceil(props.total / props.size), start + 6);
    }
    for (var i = start; i <= end; i++) {
        pager.value.push(i);
    }
}
makePager();

watch(
    props,
    () => {
        makePager();
    },
    { deep: true }
);
</script>
